package cn.coder.jdbc.mapper;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class HashMapResultMapper extends BaseResultMapper<Map<?, ?>> {
	private static final Logger logger = LoggerFactory.getLogger(HashMapResultMapper.class);

	public HashMapResultMapper(String sql, Object[] array) {
		super(sql, array, false);
	}

	@Override
	public Map<?, ?> doPreparedStatement(PreparedStatement stmt) throws SQLException {
		ResultSetMetaData metaData = stmt.getMetaData();
		if (metaData.getColumnCount() == 1)
			throw new SQLException("Not support single column result");

		int count = 0;
		ResultSet rs = stmt.executeQuery();
		Map<Object, Object> map = new HashMap<>();
		// 两列查询取全部
		if (metaData.getColumnCount() == 2) {
			while (rs.next()) {
				map.put(rs.getObject(1), rs.getObject(2));
				count++;
			}
		} else {// 多列查询取第一行
			String label;
			while (rs.next()) {
				for (int i = 0; i < metaData.getColumnCount(); i++) {
					label = metaData.getColumnLabel(i + 1);
					map.put(label, rs.getObject(label));
				}
				count++;
				break;
			}
		}
		rs.close();
		logger.debug("Result count:{}", count);
		return map;
	}

}
